<template>
  <div class="container">
    <div class="top-box box-item">
      <!-- 时间线 -->
      <div class="steps" v-if="baseForm.step">
        <el-steps style="width:1000px;" :active="baseForm.step">
          <el-step v-for="(activity, index) in stepOptions" style="cursor: pointer;" :key="index" @click="hanldeStepClick(activity)">
            <template #description>
              <div class="desc">
                <div class="title">{{ activity.content }}</div>
                <div class="state">{{ activity.stateText }}</div>
                <div class="plan">计划：{{ baseForm.createTime || '--'}}</div>
                <div class="actual">实际：{{ baseForm.passTime || '--'}}</div>
              </div>
            </template>
          </el-step>
        </el-steps>
      </div>
    </div>

    <div class="content box-item">
      <!-- 基本信息 -->
      <el-form :model="baseForm" label-width="auto" label-position="top" ref="baseFormRef" :rules="baseFormRules">
        <div class="card-title" @click="showBaseInfo = !showBaseInfo">
          项目信息
          <i class="iconfont" :class="showBaseInfo ? '':'rotate'">&#xe601;</i>
        </div>
        <div class="base-info" v-show="showBaseInfo">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="项目单号" prop="number">
                <el-input v-model="baseForm.number" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="业务日期">
                <el-input v-model="baseForm.createTime" placeholder="提交后自动生成当前时间" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="立项状态">
                <el-select v-model="baseForm.state" disabled placeholder="保存后自动生成" style="width: 100%;">
                  <el-option :label="item.label" :value="item.value" v-for="(item, index) in projectStatusOptions" :key="index" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="采购控制总金额(￥)">
                <el-input v-model="baseForm.totalAmount" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="项目名称" prop="name">
                <el-input v-model="baseForm.name" placeholder="请输入项目名称" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="采购计划" prop="planId" style="margin-bottom: 0;">
                <el-select v-model="baseForm.planId" style="width: 100%;" clearable placeholder="请选择计划" @change="handlePlanChange">
                  <el-option :label="item.name" :value="item.id" v-for="(item, index) in planOptions" :key="index" />
                </el-select>
              </el-form-item>
              <!-- <el-form-item label="采购方式" prop="procurementMethod">
                <el-select v-model="baseForm.procurementMethod" style="width: 100%" placeholder="请选择采购方式">
                  <el-option label="公开招标" :value="1" />
                </el-select>
              </el-form-item>-->
            </el-col>
            <!-- <el-col :span="6">
              <el-form-item label="项目类型" prop="type">
                <el-select v-model="baseForm.type" clearable style="width: 100%" placeholder="请选择项目类型">
                  <el-option label="调研" :value="0" />
                </el-select>
              </el-form-item>
            </el-col> -->
            <el-col :span="6">
              <el-form-item label="绑定表单" prop="needFormId">
                <el-select v-model="baseForm.needFormId" style="width: 100%" clearable placeholder="请选择项目类型">
                  <el-option :label="item.title" :value="item.id" v-for="(item, index) in bindFormOptions" :key="index" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="创建人" prop="userName">
                <el-input v-model="baseForm.userName" placeholder="请输入创建人" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            
            <el-col :span="6">
              <el-form-item label="必选资质">
                <el-select v-model="baseForm.requiredQualifications" multiple style="width: 100%" placeholder="请选择资质">
                  <el-option :label="item.name" :value="item.id + ''" v-for="(item, index) in requiredQualificationsOptions" :key="index" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="可选资质">
                <el-select v-model="baseForm.optionalQualifications" multiple style="width: 100%" placeholder="请选择资质" @change="handleOptionalQualificationsChange">
                  <el-option :label="item.name" :value="item.id + ''" v-for="(item, index) in optionalQualificationsOptions" :key="index" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="可选资质中需提供的最少资质数量" prop="optionalQualificationsMustNum">
                <el-input-number v-model="baseForm.optionalQualificationsMustNum" :min="0" :max="baseForm?.optionalQualifications?.length" />
              </el-form-item>
            </el-col>
            <el-col :span="6"></el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="18">
              <el-form-item label="采购说明">
                <el-input v-model="baseForm.description" type="textarea" placeholder="请输入采购说明" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
    </div>
    <!-- 根据步骤显示 -->
    <div class="content box-item" v-loading="baseFormLoading">
      <!-- 1快速立项 -->
      <ProjectStep1 :baseForm="baseForm" :id="id" v-if="showStep == 1" />
      <!-- 2供应商审核 -->
      <ProjectStep2 :supplierList="supplierList" :baseForm="baseForm" :id="id" v-if="showStep == 2 && !baseFormLoading" />
    </div>
    <div class="file-content box-item">
      <!-- 基本信息 -->
      <div class="card-title">附件信息</div>
      <!-- 附件信息 -->
      <div class="file-box">
        <el-button type="primary" @click="handleShowFileUpload">上传附件</el-button>
        <div class="file-list" v-if="baseForm?.annex?.length">
          <div class="file-item" v-for="(item, index) in baseForm.annex" :key="index">
            <div class="file-name" @click="handleFileDownLoad(item)">{{item.fileName}}</div>
            <div class="btns">
              <el-button type="danger" link @click="hanldeDeletefile(item)">删除</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="fixed-btns">
      <!-- <div class="btns">
        <el-button type="primary" @click="handleSave(1)">保存</el-button>
        <el-button type="primary" @click="handleSave(2)">提交</el-button>
        <el-button @click="handleGoBack">退出</el-button>
      </div>-->
      <div class="btns" v-if="pageType == 1">
        <template v-if="[0, 3].includes(baseForm.state)">
          <el-button type="primary" @click="handleSave(1)">保存</el-button>
          <el-button type="primary" @click="handleSave(2)">提交</el-button>
        </template>
        <el-button @click="handleGoBack">退出</el-button>
      </div>
      <div class="btns" v-if="pageType == 2">
        <el-button type="primary" @click="handleEdit('state', 2)">通过</el-button>
        <el-button type @click="handleEdit('state', 3)">不通过</el-button>
        <el-button @click="handleGoBack">退出</el-button>
      </div>
      <div class="btns">
        <el-button type="danger" v-if="baseForm.state != 4 && pageType == 2" @click="handleEdit('state', 4)">作废</el-button>
        <el-button type v-if="baseForm.state == 4 " @click="handleEdit('state', 0)">保存并恢复</el-button>
      </div>
    </div>
    <FilesUpload v-if="showFilesUpload" v-model:showDialog="showFilesUpload" :isPublic="true" @getFileList="insertFiles" :isToJpg="true"></FilesUpload>
  </div>
</template>
<script setup>
import { ref } from 'vue'
// import { download } from '@/utils/tools'
import ProjectStep1 from './components/ProjectStep1.vue'
import ProjectStep2 from './components/ProjectStep2.vue'
import {
  biddingProjectById,
  projectInsert,
  projectUpdate,
  projectUpdateState,
  getPlanOptions,
  getOptionalQualificationsOptions,
  biddingProcurementById,
  getBindFormOptions,
} from '@/api/bidding'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { FilesUpload } from "@ruifox-cms/components"
const route = useRoute()
const router = useRouter()
const id = route.query.id // 获取当前路由的id参数
const pageType = route.query.pageType // pageType 1 查看 2 审核
const step = route.query.step // 当前步骤

const projectStatusOptions = ref([
  { label: '立项暂存', value: 0 },
  { label: '待审核', value: 1 },
  { label: '已通过', value: 2 },
  { label: '未通过', value: 3 },
  { label: '已作废', value: 4 },
])
// 获取资质字典
const optionalQualificationsOptions = ref([])
const requiredQualificationsOptions = ref([])
const optionalQualificationsOptionsAsync = async () => {
  const res = await getOptionalQualificationsOptions()
  optionalQualificationsOptions.value = res.data
  requiredQualificationsOptions.value = res.data
}
optionalQualificationsOptionsAsync()
// 获取可选计划字典
const planOptions = ref([])
const getPlanOptionsAsync = async () => {
  const res = await getPlanOptions()
  planOptions.value = res.data
  // if(planOptions.value?.length ){
  //   baseForm.value.planId = planOptions.value[0].id
  // }
}
getPlanOptionsAsync()

const generateTimeString = () => {
  var now = new Date()
  var year = now.getFullYear()
  var month = now.getMonth() + 1 // 月份是从0开始的
  var day = now.getDate()
  var hours = now.getHours()
  var minutes = now.getMinutes()
  var seconds = now.getSeconds()

  // 将月份、日期、小时、分钟和秒数转换为两位数的字符串
  month = month < 10 ? '0' + month : month
  day = day < 10 ? '0' + day : day
  hours = hours < 10 ? '0' + hours : hours
  minutes = minutes < 10 ? '0' + minutes : minutes
  seconds = seconds < 10 ? '0' + seconds : seconds

  // 拼接成所需格式的字符串
  var timeString = year + '' + month + '' + day + '' + hours + '' + minutes + '' + seconds

  return timeString
}
// 基本信息
const baseFormRef = ref()
const baseFormRules = ref({
  number: [{ required: true, message: '请输入内容', trigger: 'blur' }],
  name: [{ required: true, message: '请输入项目名称', trigger: 'change' }],
  procurementMethod: [{ required: true, message: '请选择采购方式', trigger: 'blur' }],
  userName: [{ required: true, message: '请输入', trigger: 'blur' }],
  qualifications: [{ required: true, message: '请输入资质要求', trigger: 'blur' }],
  planId: [{ required: true, message: '请选择计划', trigger: 'change' }],
  needFormId: [{ required: true, message: '请绑定表单', trigger: 'change' }],
})
const defaultBaseForm = {
  step: 1, //步骤 计划0 立项1 ...
  number: '', //项目单号
  name: '', //项目名称
  // procurementMethod: '', //采购方式 1邀请招标 2公开招标
  state: 0, //立项状态 -1 全部 0 立项暂存 1 待审核 2 审核通过 3 审核驳回 4 已作废
  totalAmount: 0, //采购控制总金额(￥)
  userName: '', //创建人
  createTime: '', //业务日期
  requiredQualifications: [], //项目必选资质
  optionalQualifications: [], //项目可选资质
  optionalQualificationsMustNum: 1, //可选资质中需提供的最少资质数量
  planId: null, //绑定的计划
  description: '', //采购说明
  type: 0, //项目类型
  procurementItemsInfoList: [], //采购明细
  needFormId: null, //绑定表单
  contactName: '', //联系人姓名
  contactPhone: '', //联系人电话
  contactMail: '', //联系人邮箱
  unit: '', //使用单位
  address: '', //地址
  endTime: '', //确认截至时间
  annex: [], //附件信息
}
const baseForm = ref({})
const baseFormLoading = ref(false)
const biddingProjectByIdAsync = async () => {
  if (id) {
    baseFormLoading.value = true
    // 编辑
    let res = await biddingProjectById({ id })
    baseForm.value = res.data
    baseFormLoading.value = false
  } else {
    //新增
    baseForm.value = structuredClone(defaultBaseForm)
    baseForm.value.number = 'XMDH' + generateTimeString() + Math.floor(Math.random() * 10000)
  }
  setTimeout(() => {
    stepOptions.value.forEach((item) => {
      if (item.step > baseForm.value.step) {
        item.stateText = '未开始'
      } else if (item.step == baseForm.value.step) {
        item.stateText = '进行中'
      } else {
        item.stateText = '已完成'
      }
    })
  }, 0)
}
biddingProjectByIdAsync()

const showBaseInfo = ref(true) //展示基础信息
if (route.query.step > 1) showBaseInfo.value = false

// 流程时间线 1快速立项 2供方审核 3结果通知
const showStep = ref(step || 1)
const stepOptions = ref([
  {
    content: '快速立项',
    step: 1,
  },
  {
    content: '供应商报名审核',
    step: 2,
  },
  {
    content: '下载报名通过名单',
    step: 3,
  },
  {
    content: '结果通知',
    step: 4,
  },
])

const hanldeStepClick = (val) => {
  if (baseForm.value.step >= val.step) {
    showStep.value = val.step
  }
  if (showStep.value > 1) showBaseInfo.value = false
}

// 附件信息
const showFilesUpload = ref(false)
const handleShowFileUpload = () => {
  showFilesUpload.value = true
}
const insertFiles = (files) => {
  if (baseForm.value.annex == null) baseForm.value.annex = []
  files.forEach((item) => {
    baseForm.value.annex.push({
      fileName: item.name,
      fileUrl: item.url,
    })
  })
}
const hanldeDeletefile = (val) => {
  baseForm.value.annex = baseForm.value.annex.filter((item) => item.fileName != val.fileName)
}
// 下载
const handleFileDownLoad = (item) => {
  window.open(item.fileUrl, '_blank')
  // download(item.fileUrl, item.fileName)
}

// 保存 提交
const handleSave = (type) => {
  baseFormRef.value.validate(async (valid) => {
    if (!baseForm.value?.endTime) {
      ElMessage({
        message: '请填写"其他信息"=>"确认截止时间"',
        type: 'warning',
      })
      return
    }
    if (valid) {
      console.log('baseForm', baseForm.value)
      if (type == 2) {
        baseForm.value.state = 1
        baseForm.value.step += 1
      }
      let res = null
      if (id) {
        // 修改
        res = await projectUpdate(baseForm.value)
      } else {
        // 新增
        res = await projectInsert(baseForm.value)
      }
      if (res.code === 20000) {
        ElMessage({
          message: '提交成功',
          type: 'success',
        })
      }
      handleGoBack()
    } else {
      return false
    }
  })
}
// 退出
const handleGoBack = () => {
  router.push({
    path: '/bidding/project/project',
  })
}
// 审核
const handleEdit = (field, val) => {
  let text
  switch (val) {
    case 0:
      text = '恢复'
      break
    case 2:
      text = '通过'
      break
    case 3:
      text = '不通过'
      break
    case 4:
      text = '作废'
      break

    default:
      text = '操作'
      break
  }
  ElMessageBox.confirm(`<div><p style="font-size: 16px;margin-bottom: 15px;">是否确认${text}？</p></div>`, '操作确认', {
    dangerouslyUseHTMLString: true,
    confirmButtonText: '确认',
    cancelButtonText: '取消',
  }).then(async () => {
    baseForm.value[field] = val
    let res = await projectUpdateState({id: baseForm.value.id, state: val})
    if (res.code === 20000) {
      ElMessage({
        message: '操作成功',
        type: 'success',
      })
      handleGoBack()
    }
  })
}
// 供应商列表
const supplierList = ref([
  {
    id: 1,
    supplier: '供应商1', //供应商全称
    supplierCode: '111111111111111111', //供应商编码
    legalRepresentative: '法定代表人1', //法定代表人
    contact: '联系人1', //联系人
    contactPhone: '13333333333', //联系电话
    address: '地址1', //地址
    remark: '备注1', //备注
    status: 1, //状态 1待审核 2审核通过 3审核不通过
  },
  {
    id: 2,
    supplier: '供应商2', //供应商全称
    supplierCode: '111111111111111111', //供应商编码
    legalRepresentative: '法定代表人1', //法定代表人
    contact: '联系人1', //联系人
    contactPhone: '13333333333', //联系电话
    address: '地址1', //地址
    remark: '备注1', //备注
    status: 2, //状态 1待审核 2审核通过 3审核不通过
  },
  {
    id: 3,
    supplier: '供应商3', //供应商全称
    supplierCode: '111111111111111111', //供应商编码
    legalRepresentative: '法定代表人1', //法定代表人
    contact: '联系人1', //联系人
    contactPhone: '13333333333', //联系电话
    address: '地址1', //地址
    remark: '备注1', //备注
    status: 3, //状态 1待审核 2审核通过 3审核不通过
  },
])

//选择计划 查询对应的采购明细列表
const handlePlanChange = async (val) => {
  if (val) {
    let res = await biddingProcurementById({ id: val })
    baseForm.value.procurementItemsInfoList = res.data.procurementItemsInfoList
    baseForm.value.description = res.data.illustrate
    baseForm.value.userName = res.data.userName
    baseForm.value.totalAmount = res.data.totalAmount
  } else {
    baseForm.value.procurementItemsInfoList = []
    baseForm.value.description = null
    baseForm.value.userName = null
    baseForm.value.totalAmount = 0
  }
}
// 切换可选资质 调整最少数量
const handleOptionalQualificationsChange = () => {
  if (baseForm.value.optionalQualifications < baseForm.value.optionalQualificationsMustNum) {
    baseForm.value.optionalQualificationsMustNum = baseForm.value.optionalQualifications?.length
  }
}

// 获取可绑定表单
const bindFormOptions = ref([])
const handleGetbindFormOptions = async () => {
  let res = await getBindFormOptions()
  bindFormOptions.value = res.data
}
handleGetbindFormOptions()
</script>
<style scoped lang='scss'>
.container {
  width: 100%;
  position: relative;
  .box-item {
    box-sizing: border-box;
    width: 100%;
    background-color: #fff;
    flex-shrink: 0;
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
    margin-right: 10px;
    border-radius: 8px;
    box-sizing: border-box;
    padding: 15px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    margin-bottom: 15px;
  }
  .card-title {
    font-size: 18px;
    font-weight: bold;
    margin-right: 20px;
    margin-bottom: 15px;
    display: flex;
    align-items: center;
    cursor: pointer;
    i {
      margin-left: 3px;
      transition: all 0.3s;
    }
    .rotate {
      transform: rotate(180deg);
    }
  }
  .top-box {
    position: relative;
    .card-title {
      position: absolute;
      left: 15px;
      top: 50%;
      transform: translateY(-50%);
    }
  }
  .steps {
    margin-top: 10px;
    display: flex;
    justify-content: center;
    .desc {
      margin-top: 10px;
      display: flex;
      flex-direction: column;
      gap: 5px 0;
    }
  }
  .content {
    margin-top: 10px;
  }
  .file-content {
    padding-bottom: 50px;
    .file-box {
      .file-list {
        margin-top: 10px;
        display: flex;
        flex-direction: column;
        gap: 5px 0;
        .file-item {
          width: 600px;
          display: flex;
          justify-content: flex-start;
          align-items: center;
          gap: 0 10px;
          .file-name {
            max-width: 400px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            font-size: 12px;
            color: #333;
            cursor: pointer;
            &:hover {
              text-decoration: underline;
              color: $mainColor;
            }
          }
        }
      }
    }
  }
  ::v-deep(.el-form-item__label) {
    font-weight: 600;
  }
  .fixed-btns {
    position: fixed;
    z-index: 1;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    padding: 5px 10px;
    background: #fff;
    display: flex;
    align-items: center;
    gap: 0 10px;
  }
}
</style>